<template>
  <!-- 课程设计编辑页面 -->
  <div class="course-design-edit-container">
    <!-- 顶部操作栏 -->
    <a-card :bordered="false" class="top-action-bar">
      <a-row>
        <a-col :span="16">
          <a-space>
            <a-button type="primary" @click="saveExamGenerate" :loading="saving">
              <template #icon><save-outlined /></template>
              保存
            </a-button>
            <a-dropdown :trigger="['click']" placement="bottomLeft">
              <a-button>
                <template #icon><export-outlined /></template>
                导出
              </a-button>
              <template #overlay>
                <a-menu>
                  <a-sub-menu key="pdf" title="PDF">
                    <a-menu-item key="pdf-full" @click="exportAs('pdf', 'full')">
                      <file-pdf-outlined /> 完整版(含答案解析)
                    </a-menu-item>
                    <a-menu-item key="pdf-student" @click="exportAs('pdf', 'student')">
                      <file-pdf-outlined /> 学生版(无答案解析)
                    </a-menu-item>
                  </a-sub-menu>
                  <a-sub-menu key="word" title="Word">
                    <a-menu-item key="word-full" @click="exportAs('docx', 'full')">
                      <file-word-outlined /> 完整版(含答案解析)
                    </a-menu-item>
                    <a-menu-item key="word-student" @click="exportAs('docx', 'student')">
                      <file-word-outlined /> 学生版(无答案解析)
                    </a-menu-item>
                  </a-sub-menu>
                </a-menu>
              </template>
            </a-dropdown>
            <a-dropdown :trigger="['click']" placement="bottomLeft">
              <a-button>
                <template #icon><share-alt-outlined /></template>
                分享
              </a-button>
              <template #overlay>
                <a-menu>
                  <a-menu-item key="link" @click="generateShareLink">
                    <link-outlined /> 生成分享链接
                  </a-menu-item>
                  <a-menu-item key="protect" @click="showProtectModal">
                    <lock-outlined /> 密码保护
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </a-space>
        </a-col>
        <a-col :span="8" class="status-indicators">
          <a-space>
            <a-tooltip title="快捷键帮助">
              <a-button shape="circle" @click="showShortcutsModal">
                <template #icon><question-circle-outlined /></template>
              </a-button>
            </a-tooltip>
            <a-tooltip :title="saveStatus">
              <a-badge :status="saveStatus === '已保存' ? 'success' : 'processing'" />
              <span>{{ saveStatus }}</span>
            </a-tooltip>
            <a-tooltip :title="networkStatus">
              <a-badge :status="networkStatus === '在线' ? 'success' : 'warning'" />
              <span>{{ networkStatus }}</span>
            </a-tooltip>
          </a-space>
        </a-col>
      </a-row>
    </a-card>

    <a-card title="编辑课程设计" :bordered="false" class="main-edit-card">
      <!-- 标题 -->
      <div class="title-section">
        <a-input
          v-model:value="examTitle"
          placeholder="请输入测试标题"
          class="title-input"
          size="large"
        />
      </div>

      <!-- MD编辑器区域 -->
      <div class="editor-section">
        <a-row>
          <a-col :span="12" class="editor-col">
            <div class="editor-title">编辑区</div>
            <MdEditor
              v-model="markdownContent"
              @change="handleMarkdownChange"
              :toolbars="markdownToolbars"
              height="600px"
              :preview="false"
            />
          </a-col>

          <a-col :span="12" class="preview-col">
            <div class="preview-title">预览区</div>
            <div class="preview-content" v-html="htmlContent"></div>
          </a-col>
        </a-row>
      </div>

      <!-- 底部操作按钮 -->
      <div class="action-buttons">
        <a-popconfirm
          title="确定要放弃编辑？"
          ok-text="确定"
          cancel-text="取消"
          @confirm="handleCancel"
        >
          <a-button>取消</a-button>
        </a-popconfirm>
        <a-button @click="saveExamGenerate" :loading="saving">保存草稿</a-button>
        <a-dropdown :trigger="['click']" placement="bottomLeft">
          <a-button type="primary" :loading="publishing">
            发布
            <down-outlined />
          </a-button>
          <template #overlay>
            <a-menu>
              <a-menu-item key="publish-full" @click="handlePublish('full')">
                <check-circle-outlined /> 发布完整版(含答案解析)
              </a-menu-item>
              <a-menu-item key="publish-student" @click="handlePublish('student')">
                <check-circle-outlined /> 发布学生版(无答案解析)
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </div>
    </a-card>

    <!-- 分享链接弹窗 -->
    <a-modal v-model:open="shareLinkModalVisible" title="分享测试试题" @ok="copyShareLink">
      <p>生成的分享链接（有效期7天）：</p>
      <a-input v-model:value="shareLink" readonly />
      <a-divider />
      <a-checkbox v-model:checked="passwordProtected">启用密码保护</a-checkbox>
      <a-input-password
        v-if="passwordProtected"
        v-model:value="sharePassword"
        placeholder="设置访问密码"
        style="margin-top: 10px"
      />
    </a-modal>

    <!-- 快捷键提示弹窗 -->
    <a-modal
      v-model:open="shortcutsModalVisible"
      title="快捷键帮助"
      @ok="shortcutsModalVisible = false"
    >
      <a-table :dataSource="shortcuts" :columns="shortcutColumns" :pagination="false" />
    </a-modal>
    <ToTop/>
  </div>
</template>

<script lang="ts" setup>
import {
  DeleteOutlined,
  ExportOutlined,
  EyeOutlined,
  FileExcelOutlined,
  FileOutlined,
  FilePdfOutlined,
  FileWordOutlined,
  FileUnknownOutlined,
  InboxOutlined,
  LinkOutlined,
  LockOutlined,
  PlusOutlined,
  QuestionCircleOutlined,
  SaveOutlined,
  DownOutlined,
  CheckCircleOutlined,
  ShareAltOutlined,
  UploadOutlined,
} from '@ant-design/icons-vue'
import { ref, onMounted, computed, onBeforeUnmount } from 'vue'
import { message } from 'ant-design-vue'
import { marked } from 'marked'
import router from '../../../router'
import { MdEditor, type ToolbarNames } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import html2pdf from 'html2pdf.js'
import { Document, Packer, Paragraph, TextRun, SectionType } from 'docx'
import { saveAs } from 'file-saver'

import { useRoute } from 'vue-router'
import { getGenerateExamVo, updateGenerateExam } from '@/api/generateExamController'
import ToTop from '@/components/ToTop.vue'
import { BizType, generateShare } from '@/utils/share'

// 定义本地QuestionData接口，与API.GenerateExamVO保持一致
interface QuestionData {
  id?: number
  title?:string
  type?: string
  content?: string
  options?: string[]
  answer?: string
  explanation?: string
  knowledgePoints?: string[]
}

const route = useRoute()
const questionsDataList = ref<QuestionData[]>([])

// 获取试题数据
const fetchDataList = async () => {
  const id = route.params.id
  if (!id) {
    return
  }
  try {
    const params = {
      id: id,
    }
    const res = await getGenerateExamVo(params)
    if (res.data.data && res.data.code === 0) {
      questionsDataList.value = res.data.data || []
      examTitle.value = questionsDataList.value[0].title
    } else {
      message.error('获取生成测试失败')
    }
  } catch (error) {
    message.error('获取生成测试失败')
  }
}

// 备用测试数据，当API返回为空时使用
const fallbackQuestions: QuestionData[] = [
  {
    id: 1936003231472062466,
    type: '选择题',
    content: '在Socket编程中，以下关于服务器端操作的正确描述是：',
    options: [
      'A. 服务器端无需绑定端口号即可接收客户端请求',
      'B. 每个客户端连接必须创建新线程独立处理',
      'C. 可以通过同一个Socket对象同时处理多个客户端请求',
      'D. 服务器必须先启动并监听指定端口',
    ],
    answer: 'D',
    explanation:
      '服务器必须先绑定端口并进入监听状态（D正确）。A错误，服务器需要绑定端口；B错误，可用线程池或IO复用技术；C错误，普通Socket只能处理单连接',
    knowledgePoints: ['Socket编程基础', '服务器配置'],
  },
  {
    id: 1936003231472062467,
    type: '选择题',
    content: '关于TCP和UDP协议的特性，正确的是：',
    options: [
      'A. TCP提供可靠传输但不保证顺序交付',
      'B. UDP支持多播且具有拥塞控制机制',
      'C. TCP连接建立需要三次握手',
      'D. UDP头部包含16位校验和字段',
    ],
    answer: 'C',
    explanation:
      'TCP三次握手建立连接（C正确）。A错误，TCP保证顺序交付；B错误，UDP无拥塞控制；D错误，UDP校验和为可选字段',
    knowledgePoints: ['传输层协议', '网络通信原理'],
  },
  {
    id: 1936003231472062468,
    type: '选择题',
    content: '在实现客户端-服务器架构时，以下哪项属于服务器端必须实现的功能？',
    options: ['A. 动态生成HTML页面', 'B. 处理并发请求', 'C. 解析HTTP请求头', 'D. 维护会话状态'],
    answer: 'B',
    explanation:
      '服务器端需处理并发请求（B正确）。A/C/D为Web服务器特有功能，而通用服务器可能不需要',
    knowledgePoints: ['网络架构设计', '并发处理'],
  },
  {
    id: 1936003231472062469,
    type: '选择题',
    content: '进行网络应用测试时，以下哪个工具最适合抓取和分析网络数据包？',
    options: ['A. Wireshark', 'B. JUnit', 'C. Valgrind', 'D. GDB'],
    answer: 'A',
    explanation: 'Wireshark是专用网络协议分析工具（A正确）。B是单元测试框架，C/D是内存调试工具',
    knowledgePoints: ['网络测试工具', '数据包分析'],
  },
  {
    id: 1936003231472062470,
    type: '选择题',
    content: '在撰写网络应用测试报告时，必须包含以下哪项内容？',
    options: [
      'A. 网络设备的品牌型号',
      'B. 代码行覆盖率数据',
      'C. 不同负载下的响应时间',
      'D. 开发人员工作日志',
    ],
    answer: 'C',
    explanation: '性能测试需记录不同负载的响应时间（C正确）。A/B/D属于非必要信息',
    knowledgePoints: ['测试报告规范', '性能评估'],
  },
  {
    id: 1936003231472062466,
    type: '填空题',
    content: 'TensorFlow.js 支持 ________ 和 ________ 两种模式，分别适用于不同类型的机器学习任务。',
    options: [],
    answer: 'imperative, functional',
    explanation:
      'imperative 模式支持即时执行，functional 模式则用于构建静态图模型，两者适应不同的编程风格。',
    knowledgePoints: ['执行模式', 'TensorFlow.js 架构'],
  },
]

// Markdown编辑器工具栏配置
const markdownToolbars: ToolbarNames[] = [
  'bold',
  'underline',
  'italic',
  'strikeThrough',
  'title',
  'sub',
  'sup',
  'quote',
  'unorderedList',
  'orderedList',
  'codeRow',
  'code',
  'link',
  'table',
  'mermaid',
  'katex',
  'preview',
  'fullscreen',
]

// 保存状态
const saveStatus = ref('已保存')
const networkStatus = ref('在线')
const saving = ref(false)
const publishing = ref(false)
const examTitle = ref('计算机网络测试')

// 编辑器相关
const markdownContent = ref('')
const htmlContent = ref('')

// 将JSON格式的题目转换为Markdown格式
const convertQuestionsToMarkdown = (questions: QuestionData[]): string => {
  let markdown = '# 考试题目\n\n'

  // 对题目按类型分组
  const questionsByType: Record<string, QuestionData[]> = {}
  questions.forEach((question) => {
    // 确保type存在，如果不存在则使用"未分类"
    const type = question.type || '未分类'
    if (!questionsByType[type]) {
      questionsByType[type] = []
    }
    questionsByType[type].push(question)
  })

  // 为每种题型创建一个部分
  let questionNumber = 1
  for (const [type, typeQuestions] of Object.entries(questionsByType)) {
    markdown += `## ${type}\n\n`

    typeQuestions.forEach((question) => {
      markdown += `### ${questionNumber}. ${question.content || '无题目内容'}\n\n`

      // 处理选项（如果有）
      if (question.options && question.options.length > 0) {
        question.options.forEach((option) => {
          markdown += `- ${option}\n`
        })
        markdown += '\n'
      }

      markdown += `**答案:** ${question.answer || '无答案'}\n\n`
      markdown += `**解析:** ${question.explanation || '无解析'}\n\n`

      // 添加知识点标签
      if (question.knowledgePoints && question.knowledgePoints.length > 0) {
        markdown += '**知识点:** '
        markdown += question.knowledgePoints.map((kp) => `\`${kp}\``).join(', ')
        markdown += '\n\n'
      }

      markdown += '---\n\n'
      questionNumber++
    })
  }

  return markdown
}

// 生成学生版本的Markdown（无答案、解析和知识点）
const generateStudentVersion = (markdown: string): string => {
  // 移除答案、解析和知识点部分
  let studentVersion = markdown

  // 移除答案行
  studentVersion = studentVersion.replace(/\*\*答案:\*\*.*?\n\n/gs, '\n')

  // 移除解析行
  studentVersion = studentVersion.replace(/\*\*解析:\*\*.*?\n\n/gs, '\n')

  // 移除知识点行
  studentVersion = studentVersion.replace(/\*\*知识点:\*\*.*?\n\n/gs, '\n')

  return studentVersion
}

// 将Markdown格式解析回JSON格式的题目
const parseMarkdownToQuestions = (markdown: string): QuestionData[] => {
  // 这是一个简化版的解析器，实际情况可能需要更复杂的正则表达式或解析逻辑
  const questions: QuestionData[] = []

  // 分割Markdown为不同题目部分
  const sections = markdown.split('---')

  for (const section of sections) {
    if (!section.trim()) continue

    // 尝试解析题目
    try {
      // 获取题目内容
      const contentMatch = section.match(/###\s+(\d+)\.\s+(.*?)(?=\n)/s)
      if (!contentMatch) continue

      const questionNumber = contentMatch[1]
      const content = contentMatch[2].trim()

      // 获取题目类型
      const typeMatch = section.match(/##\s+(.*?)(?=\n)/)
      const type = typeMatch ? typeMatch[1].trim() : '未分类'

      // 获取选项
      const options: string[] = []
      const optionsMatches = section.matchAll(/- (.+?)(?=\n)/g)
      for (const match of optionsMatches) {
        options.push(match[1].trim())
      }

      // 获取答案
      const answerMatch = section.match(/\*\*答案:\*\*\s+(.*?)(?=\n)/s)
      const answer = answerMatch ? answerMatch[1].trim() : ''

      // 获取解析
      const explanationMatch = section.match(/\*\*解析:\*\*\s+(.*?)(?=\n\n|\n\*\*)/s)
      const explanation = explanationMatch ? explanationMatch[1].trim() : ''

      // 获取知识点
      const knowledgePointsMatch = section.match(/\*\*知识点:\*\*\s+(.*?)(?=\n|$)/s)
      const knowledgePointsText = knowledgePointsMatch ? knowledgePointsMatch[1].trim() : ''
      const knowledgePoints = knowledgePointsText
        .split(',')
        .map((kp) => kp.trim().replace(/`/g, ''))
        .filter((kp) => kp)

      // 创建题目对象并添加到结果中
      questions.push({
        id: Date.now() + Math.floor(Math.random() * 1000), // 生成临时ID
        type,
        content,
        options,
        answer,
        explanation,
        knowledgePoints,
      })
    } catch (e) {
      console.error('解析题目失败:', e)
    }
  }

  return questions
}

// 监听Markdown内容变化
const handleMarkdownChange = (content: string) => {
  // 使用marked库将Markdown转换为HTML
  const result = marked(content)
  if (typeof result === 'string') {
    htmlContent.value = result
  } else {
    // 处理异步情况，如果是Promise则等待结果
    result.then((html: string) => {
      htmlContent.value = html
    })
  }
  saveStatus.value = '未保存'
}

// 初始化
onMounted(() => {
  window.addEventListener('keydown', handleKeyDown)

  // 检测网络状态
  window.addEventListener('online', () => {
    networkStatus.value = '在线'
    message.success('网络已连接')
  })
  window.addEventListener('offline', () => {
    networkStatus.value = '离线'
    message.warning('网络已断开，将启用离线模式')
  })


  fetchDataList().then(() => {
    // 将题目数据转换为Markdown
    if (questionsDataList.value && questionsDataList.value.length > 0) {
      markdownContent.value = convertQuestionsToMarkdown(questionsDataList.value)
    } else {
      // 如果API数据为空，使用默认数据
      markdownContent.value = convertQuestionsToMarkdown(fallbackQuestions)
    }

    // 初始化HTML预览
    const result = marked(markdownContent.value)
    if (typeof result === 'string') {
      htmlContent.value = result
    } else {
      // 处理异步情况
      result.then((html: string) => {
        htmlContent.value = html
      })
    }
  })
})
onBeforeUnmount(() => {
  window.removeEventListener('keydown', handleKeyDown)
  window.removeEventListener('online', () => {})
  window.removeEventListener('offline', () => {})
})
// 保存课程设计
const saveExamGenerate = async () => {
  saving.value = true
  saveStatus.value = '保存中...'

  try {
    // 将Markdown解析回题目数据
    const parsedQuestions = parseMarkdownToQuestions(markdownContent.value)
    console.log('解析后的题目数据:', parsedQuestions)

    // 在这里可以调用API保存数据
    // await saveExam({ title: examTitle.value, questions: parsedQuestions })
    const res = await updateGenerateExam({
      id:route.params.id,
      title:examTitle.value,
      generateExamVOList:parsedQuestions,
      status:1
    })
    message.success('保存成功')
    saveStatus.value = '已保存'
  } catch (error) {
    console.error('保存失败:', error)
    message.error('保存失败，请重试')
    saveStatus.value = '保存失败'
  } finally {
    saving.value = false
  }
}

// 分享相关
const shareLinkModalVisible = ref(false)
const shareLink = ref('https://example.com/share/course/123456')
const passwordProtected = ref(false)
const sharePassword = ref('')


// 分享链接相关
const generateShareLink = async () => {
  shareLinkModalVisible.value = true
  try {
    const link = await generateShare(passwordProtected.value, {
      bizType: BizType.GENEXAM,
      bizId: route.params.id
    })
    shareLink.value = link
    console.log('分享链接:', link)
  } catch (e) {
    message.error("生成分享链接失败")
  }
}

const showProtectModal = async () => {
  shareLinkModalVisible.value = true
  passwordProtected.value = true
  try {
    const link = await generateShare(passwordProtected.value, {
      bizType: BizType.GENEXAM,
      bizId: route.params.id
    })
    shareLink.value = link
    console.log('分享链接:', link)
  } catch (e) {
    message.error("生成分享链接失败")
  }
}
const copyShareLink = () => {
  // 复制链接到剪贴板
  navigator.clipboard
    .writeText(shareLink.value)
    .then(() => {
      message.success('链接已复制到剪贴板')
      shareLinkModalVisible.value = false
    })
    .catch(() => {
      message.error('复制失败，请手动复制')
    })
}
// 快捷键相关
const shortcutsModalVisible = ref(false)
const shortcuts = [
  { key: 'Ctrl+S', description: '保存方案' },
  { key: 'Alt+I', description: '插入资源' },
  { key: 'Ctrl+E', description: '导出PDF' },
  { key: 'Ctrl+D', description: '复制章节' },
  { key: 'F1', description: '显示帮助' },
]
const shortcutColumns = [
  { title: '快捷键', dataIndex: 'key', key: 'key' },
  { title: '功能描述', dataIndex: 'description', key: 'description' },
]

// 显示快捷键帮助
const showShortcutsModal = () => {
  shortcutsModalVisible.value = true
}

// 导出功能
const exportAs = async (type: string, version: 'full' | 'student') => {
  try {
    if (type === 'pdf') {
      await exportToPdf(version)
    } else if (type === 'docx') {
      await exportToWord(version)
    }
    message.success(`成功导出${version === 'full' ? '完整版' : '学生版'}${type.toUpperCase()}`)
  } catch (error) {
    console.error('导出失败:', error)
    message.error('导出失败，请重试')
  }
}

// 导出为PDF
const exportToPdf = async (version: 'full' | 'student') => {
  // 准备要导出的HTML内容
  const element = document.createElement('div')

  // 根据版本类型选择内容
  let contentHtml = ''
  if (version === 'full') {
    contentHtml = htmlContent.value
  } else {
    // 生成学生版（无答案解析）
    const studentMarkdown = generateStudentVersion(markdownContent.value)
    const result = marked(studentMarkdown)
    if (typeof result === 'string') {
      contentHtml = result
    } else {
      contentHtml = await result
    }
  }

  element.innerHTML = `
    <h1 style="text-align: center">${examTitle.value || '考试题目'}</h1>
    <div>${contentHtml}</div>
  `

  // 配置html2pdf选项
  const opt = {
    margin: 15,
    filename: `${examTitle.value || '考试题目'}_${version === 'full' ? '完整版' : '学生版'}.pdf`,
    image: { type: 'jpeg', quality: 0.98 },
    html2canvas: { scale: 2, useCORS: true },
    jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' },
  }

  // 生成PDF
  await html2pdf().from(element).set(opt).save()
}

// 导出为Word
const exportToWord = async (version: 'full' | 'student') => {
  try {
    // 获取文档内容
    let markdownToExport = ''
    if (version === 'full') {
      markdownToExport = markdownContent.value
    } else {
      markdownToExport = generateStudentVersion(markdownContent.value)
    }

    // 解析Markdown为结构化数据
    const questions = parseMarkdownToQuestions(markdownToExport)

    // 按题型分组
    const questionsByType: Record<string, QuestionData[]> = {}
    questions.forEach((question) => {
      if (!questionsByType[question.type]) {
        questionsByType[question.type] = []
      }
      questionsByType[question.type].push(question)
    })

    // 准备文档内容
    const children: Paragraph[] = []

    // 添加标题
    children.push(
      new Paragraph({
        text: examTitle.value || '考试题目',
        heading: 'Title',
        alignment: 'center',
      }),
    )

    // 为每种题型创建一个部分
    let questionNumber = 1
    for (const [type, typeQuestions] of Object.entries(questionsByType)) {
      // 添加题型标题
      children.push(
        new Paragraph({
          text: `${getRomanNumeral(Object.keys(questionsByType).indexOf(type) + 1)}、${type}`,
          heading: 'Heading1',
          spacing: {
            before: 400,
            after: 200,
          },
        }),
      )

      typeQuestions.forEach((question) => {
        // 添加题目内容
        children.push(
          new Paragraph({
            text: `${questionNumber}. ${question.content}`,
            heading: 'Heading2',
            spacing: {
              before: 200,
              after: 100,
            },
          }),
        )

        // 处理选项（如果有）
        if (question.options && question.options.length > 0) {
          question.options.forEach((option) => {
            children.push(
              new Paragraph({
                text: option,
                bullet: {
                  level: 0,
                },
                spacing: {
                  before: 80,
                  after: 80,
                },
              }),
            )
          })
        }

        // 添加答案和解析（如果是完整版）
        if (version === 'full') {
          if (question.answer) {
            children.push(
              new Paragraph({
                children: [
                  new TextRun({
                    text: '答案: ',
                    bold: true,
                  }),
                  new TextRun({
                    text: question.answer,
                  }),
                ],
                spacing: {
                  before: 100,
                  after: 100,
                },
              }),
            )
          }

          if (question.explanation) {
            children.push(
              new Paragraph({
                children: [
                  new TextRun({
                    text: '解析: ',
                    bold: true,
                  }),
                  new TextRun({
                    text: question.explanation,
                  }),
                ],
                spacing: {
                  before: 100,
                  after: 100,
                },
              }),
            )
          }

          // 添加知识点
          if (question.knowledgePoints && question.knowledgePoints.length > 0) {
            children.push(
              new Paragraph({
                children: [
                  new TextRun({
                    text: '知识点: ',
                    bold: true,
                  }),
                  new TextRun({
                    text: question.knowledgePoints.join(', '),
                  }),
                ],
                spacing: {
                  before: 100,
                  after: 100,
                },
              }),
            )
          }
        }

        // 添加分隔线
        children.push(
          new Paragraph({
            text: '',
            border: {
              bottom: {
                color: '999999',
                space: 1,
                style: 'single',
                size: 6,
              },
            },
            spacing: {
              before: 200,
              after: 200,
            },
          }),
        )

        questionNumber++
      })
    }

    // 创建一个新的Word文档
    const doc = new Document({
      sections: [
        {
          properties: {},
          children: children,
        },
      ],
    })

    // 生成并下载Word文档
    const buffer = await Packer.toBlob(doc)
    saveAs(
      buffer,
      `${examTitle.value || '考试题目'}_${version === 'full' ? '完整版' : '学生版'}.docx`,
    )
  } catch (error) {
    console.error('导出Word文档时出错:', error)
    message.error('导出Word文档失败，请重试')
  }
}

// 获取罗马数字
const getRomanNumeral = (num: number): string => {
  const romanNumerals = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X']
  return romanNumerals[num - 1] || num.toString()
}

// 取消编辑
const handleCancel = () => {
  router.push('/teacher/exam_generation')
}

// 发布课程设计
const handlePublish = async (version: 'full' | 'student') => {
  publishing.value = true
  try {
    // 将Markdown解析回题目数据
    const parsedQuestions = parseMarkdownToQuestions(markdownContent.value)

    // 根据版本类型处理数据
    let publishData
    if (version === 'full') {
      publishData = {
        title: examTitle.value,
        questions: parsedQuestions,
        version: 'full',
      }
    } else {
      const res = await updateGenerateExam({
        id:route.params.id,
        status:2
      })
      if(res.data.data && res.data.code === 0){

      }else{
        message.error("发布失败")
        return
      }


      // 学生版本移除答案、解析和知识点
      const studentQuestions = parsedQuestions.map((q) => ({
        ...q,
        answer: '',
        explanation: '',
        knowledgePoints: [],
      }))

      publishData = {
        title: examTitle.value,
        questions: studentQuestions,
        version: 'student',
      }
    }

    console.log('发布数据:', publishData)
    // 在这里调用API发布数据
    // await publishExam(publishData);

    message.success(`${version === 'full' ? '完整版' : '学生版'}发布成功`)
    router.push('/teacher/exam_generation')
  } catch (error) {
    console.error('发布失败:', error)
    message.error('发布失败，请重试')
  } finally {
    publishing.value = false
  }
}

const handleKeyDown = (e: KeyboardEvent) => {
  // Ctrl+S: 保存
  if (e.ctrlKey && e.key === 's') {
    e.preventDefault()
    saveExamGenerate()
  }

  // 快捷键提示
  if (e.key === 'F1') {
    e.preventDefault()
    showShortcutsModal()
  }
}

</script>

<style scoped>
.course-design-edit-container {
  padding: 15px;
}
.top-action-bar {
  margin-bottom: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}
.status-indicators {
  text-align: right;
}
.title-input {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 16px;
}
.editor-section {
  margin: 16px 0;
}
.editor-col,
.preview-col {
  padding: 0 8px;
}
.editor-title,
.preview-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  padding: 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
}
.preview-content {
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  padding: 16px;
  min-height: 600px;
  max-height: 600px;
  overflow-y: auto;
  background-color: white;
}
.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}
</style>
